const sd = require('silly-datetime');//?生成时间格式
const crypto = require('crypto');

let server = function (app, db) {
    //?Cookie查询
    const View_Cookie = function (request, calka) {
        db.query('select * from login where UserCookie=\'' + request.cookies.DOM_Cookie + '\'', function (err, data) {
            calka(err, data)
        })
    }

    //?收藏操作</collection>
    app.post('/collection/:op', function (request, response) {
        View_Cookie(request, function (err, data) {
            if (err) {
                console.log(err);
                response.send({ "code": -1, "result": 'error' })
            } else {
                if (data[0]){
                    switch (request.params.op) {
                        case 'insert':
                            db.query('select count(*) from collection where FoodID=? and UserID=?', [request.body.FoodID, data[0]['UserID']], function (err, data1) {
                                if (err) {
                                    console.error(err);
                                    response.send({ "code": -1, "data": "error" })
                                } else {
                                    if (data1[0]['count(*)'] == 0) {//判断是否已经收藏
                                        db.query('insert collection values(?,?)', [request.body.FoodID, data[0]['UserID']], function (err, data_) {
                                            if (err) response.send({ "code": -1, "data": "error" });
                                            else response.send({ "code": 0, "data": "OK" });
                                        })
                                    } else {
                                        response.send({ "code": 0, "data": "已收藏" })
                                    }
                                }
                            })

                            break;
                        case 'select':
                            db.query('select FoodID,UserID from collection where UserID=' + data[0]['UserID'], function (err, data_) {
                                if (err) response.send({ "code": -1, "data": "error" });
                                else response.send({ "code": 0, "data": data_ });
                            })
                            break;
                        case 'delete':
                            console.log('delete from collection where FoodID=' + request.body.FoodID + ' and UserID=' + data[0]['UserID'] + ' ');
                            db.query('delete from collection where FoodID=? and UserID=? ', [request.body.FoodID, data[0]['UserID']], function (err, data) {
                                if (err) {
                                    response.send({ "code": -1, "data": "error" });
                                } else response.send({ "code": 0, "data": "OK" });

                            })
                            break
                        default:
                            response.send({ "code": -1, "data": "error" });
                            console.log('error');
                    }
                }else response.send({ "code": -1, "data": "重新登录" });
                    
            }

        })
    })

    //?菜谱类别</class>
    app.post('/class', function (request, response) {
        View_Cookie(request, function (err, data) {
            if (err) {
                console.log(err);
                response.send({ "code": -1, "result": 'error' })
            } else {
                //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                db.query('select * from class', function (err, data) {
                    response.send({ "code": 0, "data": data })
                })
                //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
            }
        })
    })

    //?获取所有菜谱
    app.post("/recipes", function (request, response) {
        if (request.body.FoodName) {
            db.query('select * from recipe where FoodName like \'%' + request.body.FoodName + '%\'', function (err, data) {
                if (err) console.error(err);

                response.send({ "code": 0, "data": data })
            })
        } else if (request.body.FoodID) {
            db.query('select * from recipe where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                if (err) console.error(err);
                if (data[0])
                    response.send({ "code": 0, "data": data[0] })
                else
                    response.send({ "code": -1, "data": 'error' })

            })
        }
        else {
            db.query('select ClassID,FoodID,FoodName,Samplefigure,Release_time,UserID  from recipe', function (err, data) {
                response.send({ "code": 0, "data": data })
            })
        }

    })

    //?获取发布菜谱
    app.post('/recipese/User', function (request, response) {
        View_Cookie(request, function (err, data) {
            if (data[0]) {
                db.query('select FoodID,Practice,Message,FoodName,Release_time,CollectionNum from recipe where UserID=' + data[0].UserID, function (err, data1) {
                    if (err) console.error(err);
                    if (data1[0]) {
                        response.send({ "code": 0, "data": data1 })
                    }
                    else response.send({ "code": 1, "data": '您还未发布菜单' })
                })
            } else {
                response.send({ "code": -1, "data": 'error' })

            }
        })

    })

    //?菜谱操作</recipe>
    app.post('/recipe/:operation', function (request, response) {
        View_Cookie(request, function (err, data) {
            if (err) {
                console.error(err);
                response.send({ "code": -1, "result": 'error' })
            } else {
                //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                if (data[0]) {
                    switch (request.params.operation) {
                        case 'insert':
                            const md5 = crypto.createHash('md5');//?生成md5实例（一次性）
                            let time__ = new Date().getTime();//?时间戳
                            const FoodID = md5.update(String(parseInt(time__ * 3000))).digest('hex');//?md5加密
                            // console.log(FoodID);
                            var updatetimes = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                            console.log(updatetimes);
                            db.query('insert recipe(Release_time,FoodID,FoodName,practice,Formula,UserID,ClassID) values(?,?,?,?,?,?,?)',
                                [
                                    updatetimes,
                                    FoodID,
                                    request.body.FoodName,
                                    request.body.practice,
                                    request.body.Formula,
                                    data[0].UserID,
                                    request.body.ClassID,
                                ], function (err, data) {
                                    if (err) {
                                        console.error(err);
                                        // console.log(request.body.Formula);
                                        response.send({ "code": -1, "result": 'error' })
                                    } else {
                                        console.log(data);
                                        if (data['affectedRows'] == 1)
                                            response.send({ "code": 0, "FoodID": FoodID })
                                        else response.send({ "code": 0, "result": "error" })
                                    }
                                })
                            break
                        case 'select':
                            const re = new RegExp(/(\d+)/g)
                            let sql_ = 'select * from recipe where'
                            while (re.lastIndex < request.body.ClassID.length) {
                                sql_ += ' ClassID=' + re.exec(request.body.ClassID)[0] + ' or'//?拼接条件语句
                            }
                            sql_ = sql_.substring(0, sql_.length - 3)//?截取字符串有效部分
                            db.query(sql_, function (err, data) {
                                if (err) {
                                    console.error(err);
                                    response.send({ "code": -1, "result": 'error' })
                                } else {
                                    response.send(data[0])
                                }
                            })
                            break
                        case 'update':
                            db.query('update recipe set FoodName=?,Samplefigure=?,Formula=?,ClickNum=?,Message=?,ClassID=? where FoodID=?',
                                [
                                    updatetimes,
                                    request.body.FoodName,
                                    request.body.Samplefigure,
                                    request.body.Formula,
                                    request.body.ClickNum,
                                    request.body.Message,
                                    request.body.ClassID,
                                    request.body.FoodID,
                                ]
                                , function (err, data) {
                                    if (err) {
                                        console.error(err);
                                        response.send({ "code": -1, "result": 'error' })
                                    } else {
                                        response.send({ "code": 0, "result": "success" })
                                    }
                                })
                            break
                        case 'delete':
                            db.query('delete from recipe where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                                if (err) {
                                    console.error(err);
                                    response.send({ "code": -1, "result": 'error' })
                                } else {
                                    console.log(data);
                                    response.send({ "code": 0, "result": "success" })
                                }
                            })
                            break
                        default:
                            response.send({ "code": -1, "result": 'error' })
                            console.log('error');
                    }
                    //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                } else {
                    response.send({ "code": -1, "result": 'error' })
                    console.log('error');
                }

            }
        })
    })

    //?留言</message>
    app.post('/message/:way', function (request, response) {
        if (request.params.way == 'select') {
            db.query('select Message from recipe where FoodID=?', [request.body.FoodID], function (err, data) {
                if (err) {
                    response.send({ "code": -1, "result": 'error' })
                } else {
                    if(data[0])
                    response.send({ "code": 0, "data": data[0]['Message'] })
                    else response.send({ "code": 0, "data": data[0] })
                }
            })
        } else
            View_Cookie(request, function (err, data) {
                if (data[0]) {
                    let userid_data = data[0].UserID
                    if (err) {
                        console.log(err);
                        response.send({ "code": -1, "result": 'error' })
                    } else {
                        //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                        let message_data = {
                            userid: request.body.userid,
                            username: request.body.username,
                            msg: request.body.message,
                            tiem_: request.body.tiem_
                        }
                        switch (request.params.way) {
                            case 'select':
                                console.log(request.body.FoodID);
                                db.query('select Message from recipe where FoodID=\'?\'', [request.body.FoodID], function (err, data) {
                                    if (err) {
                                        console.log(err);
                                        response.send({ "code": -1, "result": '错误' })
                                    } else {
                                        response.send({ "code": 0, "data": data[0]['Message'] })
                                    }
                                })
                                break
                            case 'insert_update':
                                console.log('select Message from recipe where FoodID=\'' + request.body.FoodID + '\'');
                                db.query('select Message from recipe where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                                    console.log(data[0].Message);
                                    let old_message_data = data[0].Message
                                    old_message_data = JSON.parse(old_message_data)//?字符串转对象
                                    let time_ = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');//?时间
                                    db.query('select UserName from user where UserID=' + userid_data, function (err, data2) {
                                        old_message_data[userid_data] =
                                        {
                                            "userid": userid_data,
                                            "username": data2[0].UserName,
                                            "msg": request.body.message,
                                            "time_": time_
                                        }//?添加字段
                                        console.log(old_message_data);
                                        let sql_str = JSON.stringify(old_message_data)//?对象转字符串
                                        db.query('update recipe set Message =\'' + sql_str + '\' where FoodID=\'' + request.body.FoodID + '\'', function (err, data) {
                                            if (err) {
                                                console.log(err);
                                                response.send({ "code": -1, "result": 'error' })
                                            } else {
                                                console.log(data);
                                                response.send({ "code": 0, "data": "success" })
                                            }
                                        })
                                    })

                                })
                                break
                            case 'delete':
                                db.query('select Message from recipe where FoodID=?', [request.body.FoodID], function (err, data) {
                                    let old_message_data = data[0]['Message']
                                    old_message_data = JSON.parse(old_message_data)//?字符串转对象
                                    delete old_message_data[request.body.userid]//?添加字段
                                    let sql_str = JSON.stringify(old_message_data)//?对象转字符串
                                    db.query('update recipe set Message =\'' + sql_str + '\' where FoodID=' + request.body.FoodID, function (err, data) {
                                        if (err) {
                                            console.log(err);
                                            response.send({ "code": -1, "result": 'error' })
                                        } else {
                                            console.log(data);
                                            response.send({ "code": 0, "data": "success" })
                                        }
                                    })
                                })
                                break
                            default:
                                response.send({ "code": -1, "result": 'error' })
                                console.log('error');
                        }
                        //?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?//?/
                    }
                } else
                    response.send({ "code": -1, "result": '未登录' })
            })
    })
}
module.exports = server